package logs

import (
	"ckeadm/util"
	"fmt"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"os"
	"strings"

	ckeadmv1beta1 "ckeadm/cmd/apis/v1alpha1"
	"ckeadm/cmd/runner"
	"ckeadm/constants"
	"github.com/urfave/cli"
)

func StatusCommand() cli.Command {
	var statusFlags = []cli.Flag{
		runner.ConfigPathFlag,
		runner.LogLevelFlag,
		runner.CacheDirFlag,
	}

	return cli.Command{
		Name:   "status",
		Usage:  "Bring the cluster install info",
		Action: runStatus,
		Flags:  statusFlags,
	}
}

// runKubeletStart executes kubelet start logic.
func runStatus(ctx *cli.Context) error {
	//if /var/log/components/ckeadm-status/{{clusterName}}/create.log exists, go to new logic
	ckeCluster := new(ckeadmv1beta1.CkeCluster)
	err := runner.GetCkeClusterFromFile(ctx.String("f"), ckeCluster)
	if err != nil {
		logrus.Errorf("failed to read ckeCluster from file, %s\n", err.Error())
		return err
	}
	filePath := fmt.Sprintf("%s/ckeadm-status/%s/", constants.CkeComponentLogPath, ckeCluster.Name)
	if util.Exists(filePath) {
		return runner.ShowInstallStatus(filePath)
	} else {
		return runner.CkeadmLogsRunner(ctx, os.Stdout, constants.AnsibleUpDoneFile, GetInstallMsgsFromLocal(ctx))
	}
}

func GetInstallMsgsFromLocal(ctx *cli.Context) runner.GetInstallMsgsFunction {
	return func(name, ip, clusterId, doneFile string) (logs []string) {
		context, _ := ioutil.ReadFile(fmt.Sprintf("%s/%s/%s.%s", ctx.String("cachedir"), clusterId, name, doneFile))
		return runner.FilterSpace(strings.Split(strings.ReplaceAll(string(context), "\r", ""), "\n"))
	}
}
